#include <iostream>
#include <string>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include <memory>
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "NetCal.hpp"
#include "Protocol.hpp"
#include "Log.hpp"

using namespace socket_ns;
using namespace log_ns;

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        LOG(INFO,"./tcpclient serverip serverport\n");
        exit(2);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    SockSPtr sock = std::make_shared<TcpSocket>();
    if(!sock->BuildClientSocket(serverip,serverport))
    {
        std::cerr<<"connect error"<<std::endl;
    }

    int  cnt = 3;
    while(cnt--)
    {
        std::cout << "========================================" << std::endl;
        //1. 创建请求
        std::shared_ptr<Request> req = Factory::BuidRequestDefault();
        req->_x = 10;
        req->_y = 20;
        req->_oper = '+';

        //2. 序列化
        std::string requeststr;
        req->Serialize(&requeststr);
        std::cout << requeststr <<std::endl;

        //3. 添加报头
        requeststr = Encode(requeststr);
        std::cout <<requeststr <<std::endl;

        //4. 发送请求
        sock->Send(requeststr);


        //5. 接受请求
        std::string packagestr;
        sock->Recv(&packagestr);
        std::cout << packagestr <<std::endl;

        //6. 解析报文
        packagestr = Decode(packagestr);

        //7. 反序列化
        std::shared_ptr<Response> resp = Factory::BuidResponseDefault();
        resp->Deserialize(packagestr);

        std::cout << resp->_result<<std::endl;
    }   
    return 0;
}